package ServerPack;
/**
 * @(#)Server.java
 *
 * Server application
 *
 * @author
 * @version 1.00 2013/6/29
 */
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;

import javax.swing.*;

import java.awt.event.*;
public class Server  {
		InetAddress i;
		String name;
		DatagramPacket packet;
		DatagramSocket DGsocket = null;
		static JFrame frame = new JFrame("Server");
		private Socket socket=null;
		private JTextField jtf = new JTextField();
		private String message="null";
        private BufferedReader in;
        private PrintWriter out;
        ServerSocket serverSocket;
       	InetAddress group;
       	String inetadd;
       	MulticastSocket multisocket;
       	byte[] buf = new byte[256];
        JPanel p;
        int retry=0;
        File fileToSend;
		JFileChooser fileChooser;

	// Text area for displaying contents
	private JTextArea jta = new JTextArea();
		//Client p =
		//	 new Client().ShowFrame();


	//	Thread runner;
 	public static void main(String[] args) {
 		new Server();
 	}


	 public Server() {
 		// Place text area on the frame
		frame.setLayout(new BorderLayout());
		frame.add(new JScrollPane(jta), BorderLayout.CENTER);

		p = new JPanel();
 		p.setLayout(new BorderLayout());
 		p.add(new JLabel("Enter message: "), BorderLayout.WEST);
 		p.add(jtf, BorderLayout.CENTER);
 		jtf.setHorizontalAlignment(JTextField.RIGHT);
 		jtf.addActionListener(new TextFieldListener());

 		frame.add(p, BorderLayout.SOUTH);
 		//setTitle("Server");
 		frame.setLocationByPlatform(true);
 		frame.setSize(500, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 		frame.setVisible(true); // It is necessary to show the frame here!
		name = JOptionPane.showInputDialog(frame,"Enter your name.","Anonymous");
		
 		try {
		 	// Create a server socket


			Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

    		while (e.hasMoreElements()){

        		NetworkInterface n = e.nextElement();
        		System.out.println(n.getName());
        		Enumeration<InetAddress> ee = n.getInetAddresses();

        		while (ee.hasMoreElements()){
	
	            	i = ee.nextElement();
	           		// System.out.println(i.getHostAddress());
	           		char  inet = i.getHostAddress().toString().charAt(1);
				
	          	 	System.out.println("inetadd: "+i + " lllllllo23123  " +i.getHostAddress().toString().charAt(1) + " enitchar at"+ inet  );
					
		            if(inet==('9')){
						inetadd = JOptionPane.showInputDialog(frame,"Enter IP Address",i.getHostAddress());
						InetAddress.getByName(inetadd);
						serverSocket = new ServerSocket(4448,100,i);

            	}
        		}
    		}

 		jta.append("Server started at " + new Date() + '\n');
		jta.append( "Server address:  "+inetadd+'\n' );


		//System.out.println("server socket inetaddr: "+ socket.getInetAddress());

		multisocket = new MulticastSocket(4448);
 		group = InetAddress.getByName("230.0.0.1");
 		multisocket.joinGroup(group);
		
		// creates Multicast Server for Multicast configure Clients
		runBroadCast();
		socket = serverSocket.accept();
		new Thread(new acceptClient()).start();
		
		// waits for client to connect with server
		while(socket==null){}
 	
 		// Create bufferedReader input stream
		InputStreamRead();
 		}
 	catch(IOException ex) {
			System.err.println("err  Server 1111r54:     "+ex);
		 }
 	}

	public void InputStreamRead(){
		try{
			in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));

				System.out.println("wait InputStream");

 				while ((message = in.readLine()) != null) {
 					jta.append(message + "\n");
 					out = new PrintWriter(socket.getOutputStream(), true);
 					out.println(""+message);
 					broadCast();
 					}
		}
 		catch(IOException ex) {
			System.err.println("err InputStreamRead 15422: "+ex);

	 	}
	 }
	 public class acceptClient implements Runnable{
	 	public void run(){
 			try{
 				while(true){
 					socket = serverSocket.accept();
 					jta.append("Client accepted: " + '\n');
 					}
 				}
 			catch (IOException ex) {
 			jta.append("err: acceptClient  93932 "+ex.toString() + '\n');
 			}
 		}
	 }
	private class TextFieldListener implements ActionListener {
 	public void actionPerformed(ActionEvent e) {
 		try {
 		message=jtf.getText();
 		System.out.println("gettext from txt field: "+message );
 		//	message.trim();
 		if(message.equalsIgnoreCase("")){
 			return;
 		}
 		System.out.println("Server: "+message + "    socket "+ socket);

 		if(socket==null||socket.toString()=="Socket[unconnected]"){
 		System.out.println("broadcasting: "+message);
 		broadCast();
		 jtf.setText(null);
 			return;
 		}
 		 out = new PrintWriter(socket.getOutputStream(), true);
        // out.flush();
         broadCast();
	     out.println(message);
		 jtf.setText(null);

		 }
 	catch (IOException ex) {
		System.err.println("TextFieldListener error 3: "+ex);
		 jtf.setText(null);
		 p.revalidate();
	 }
 		jtf.setText(null);
 		p.revalidate();
 		}
 	}
 	public void runBroadCast(){
 		new Thread(new listenBroadCast()).start();
 	}
 	public void broadCast(){
 		try {
 				message = name +":  "+message;
              	System.out.println("broadcasting");
                buf = message.getBytes();
		    	DGsocket = new DatagramSocket();
                packet = new DatagramPacket(buf, buf.length, group, 4448);

               // broadcasting message
                multisocket.send(packet);
   			}
   			catch (IOException e) {
                System.out.println("err: broadCast 10101 "+ e);
            	}
 	}
 	public class listenBroadCast implements Runnable{

 		public void run(){
 		try {

        @SuppressWarnings("resource")
		MulticastSocket socket = new MulticastSocket(4448);
        InetAddress address = InetAddress.getByName("230.0.0.1");
		socket.joinGroup(address);

        DatagramPacket packet;


		while(true) {
	    byte[] buf = new byte[256];
            packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);

            message = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Quote of the Moment: " + message);
            jta.append(message + '\n');
			}
            }
   			catch (IOException e) {
                System.out.println("err: listenBroadCast 2101 "+ e);
            	}
 		}
 	}

 }
